﻿using SwParaPlatform2.logger;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SwParaPlatform2.dlgUIConfig
{
    public class UIConfigModel : IModel
    {
        private static UIConfigModel instance;
        private readonly ISwParaInterface _commonInterface;

        public event EventHandler GridDataChanged;
        public event EventHandler SelectParaChanged;
        public event EventHandler SelectViewFilePathChanged;
        public event EventHandler<int> DoSelectIndex;
        public List<string> DataOrder { get; private set; }
        public List<string> InputTypeList { get; private set; }
        private Dictionary<string, Dictionary<string, object>> dUIConfigData;
        public string sSelectPara;
        public string sSelectViewFilePath;

        public UIConfigModel()
        {
            _commonInterface = new SwParaInterface();
            InputTypeList = new List<string> { "自由填写", "下拉列表（自定义）", "下拉列表（等差）" };
            DataOrder = new List<string>();
        }

        public void ClearData(bool bClearAllData)
        {
            GridDataChanged = null;
            SelectParaChanged = null;
            DoSelectIndex = null;
            sSelectPara = null;
            if (bClearAllData)
            {
                dUIConfigData = new Dictionary<string, Dictionary<string, object>>();
            }
        }

        public static UIConfigModel Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new UIConfigModel();
                }
                return instance;
            }
        }

        public static void Reset()
        {
            instance = null;
        }

        public void AddEditRow(Dictionary<string, object> data)
        {
            foreach (var key in data.Keys)
            {
                if (dUIConfigData.ContainsKey(key))
                {
                    var subData = data[key] as Dictionary<string, object>;
                    foreach (var subKey in subData.Keys)
                    {
                        if (dUIConfigData[key].ContainsKey(subKey))
                        {
                            dUIConfigData[key][subKey] = subData[subKey];
                        }
                        else
                        {
                            dUIConfigData[key].Add(subKey, subData[subKey]);
                        }
                    }
                }
                else
                {
                    var newSubData = new Dictionary<string, object>();
                    var subData = data[key] as Dictionary<string, object>;
                    foreach (var subKey in subData.Keys)
                    {
                        newSubData[subKey] = subData[subKey];
                    }
                    dUIConfigData[key] = newSubData;
                    DataOrder.Add(key);
                }
            }
            OnGridDataChanged();
        }

        public void OnSelectRow(string sPara)
        {
            sSelectPara = sPara;
            OnSelectParaChanged();
        }
        
        public void OnSelectMainViewPic(string viewFilePath)
        {
            sSelectViewFilePath = viewFilePath;
            OnRefreshRecordDataPic();
        }

        public void OnRefreshRecordDataPic()
        {
            foreach (var subDict in dUIConfigData.Values)
            {
                subDict["示例图"] = sSelectViewFilePath;
            }
            OnGridDataChanged();
        }

        public void DoSelectRow(int iIndex)
        {
            DoSelectIndex?.Invoke(this, iIndex);
        }

        public void DelEditRow()
        {
            if (dUIConfigData.ContainsKey(sSelectPara))
            {
                dUIConfigData.Remove(sSelectPara);
                if (DataOrder.Contains(sSelectPara))
                {
                    DataOrder.Remove(sSelectPara);
                }
                Logger.Instance.Log($"键 {sSelectPara} 已被成功删除。");
                OnGridDataChanged();
            }
            else
            {
                Logger.Instance.Log($"键 {sSelectPara} 不存在于字典中。");
            }
        }

        public void SaveData()
        {
            string filePath = XmlHandler.GetFilePath();
            DataStore.Instance.UIConfigData = dUIConfigData;
            //为了不重复打开/关闭模型文件，完成UI配置时先缓存UI数据，等完成规则配置时再一起打包
        }

        public void LoadData()
        {
            string rootElementName = "UIConfig";
            var loadedDictionary = XmlHandler.ReadDictionaryFromXml(rootElementName);

            if (loadedDictionary != null)
            {
                foreach (var outerItem in loadedDictionary)
                {
                    Logger.Instance.Log($"mduiconfig - LoadData {outerItem.Key}:");
                    foreach (var innerItem in outerItem.Value)
                    {
                        Logger.Instance.Log($"mduiconfig - LoadData   {innerItem.Key}: {innerItem.Value}");
                        if (innerItem.Value is List<string> list)
                        {
                            Logger.Instance.Log("mduiconfig - LoadData   List Values: " + string.Join(", ", list));
                        }
                    }
                }

                SetUIConfigData(loadedDictionary);
            }
        }

        public void LoadAllData()
        {
            _commonInterface.LoadAllData();
        }

        public void SetUIConfigData(Dictionary<string, Dictionary<string, object>> dData)
        {
            if(dData == null)
            {
                dData = new Dictionary<string, Dictionary<string, object>>();
            }
            dUIConfigData = dData;
            LoadOrder();
            OnGridDataChanged();
        }

        public void LoadOrder()
        {
            DataOrder = new List<string>();
            // 使用 LINQ 按照二级字典中的“序号”键的值对一级字典进行排序
            var sortedDict = dUIConfigData.OrderBy(kv =>
            {
                if (kv.Value.ContainsKey("序号"))
                {
                    return Convert.ToInt32(kv.Value["序号"]);
                }
                return int.MaxValue; // 如果没有“序号”键，则将其放在最后
            });

            // 将排序后的一级字典的 key 添加到列表中
            foreach (var kv in sortedDict)
            {
                DataOrder.Add(kv.Key);
            }
        }

        public void UpBtn_Click()
        {
            if (sSelectPara != null)
            {
                int selectedIndex = DataOrder.IndexOf(sSelectPara);
                if (selectedIndex > 0) // 判断是否可以向上移动
                {
                    SwapItems(selectedIndex, selectedIndex - 1);
                    DoSelectRow(selectedIndex - 1);
                }
            }
        }

        public void DownBtn_Click()
        {
            if (sSelectPara != null)
            {
                int selectedIndex = DataOrder.IndexOf(sSelectPara);
                if (selectedIndex < DataOrder.Count - 1) // 判断是否可以向下移动
                {
                    SwapItems(selectedIndex, selectedIndex + 1);
                    DoSelectRow(selectedIndex + 1);
                }
            }
        }

        public void SwapItems(int index1, int index2)
        {
            // 交换列表中的元素
            string temp = DataOrder[index1];
            DataOrder[index1] = DataOrder[index2];
            DataOrder[index2] = temp;

            // 更新列表框的显示
            OnGridDataChanged();
        }



        public void SaveOrder(List<string> lOrder)
        {
            DataOrder = lOrder;
        }

        protected virtual void OnGridDataChanged()
        {
            GridDataChanged?.Invoke();
        }
        
        protected virtual void OnSelectParaChanged()
        {
            SelectParaChanged?.Invoke();
        }

        protected virtual void OnSelectViewFilePathChanged()
        {
            SelectViewFilePathChanged?.Invoke();
        }

        #region get接口
        public List<string> GetInputTypeList()
        {
            return InputTypeList;
        }

        public Dictionary<string, Dictionary<string, object>> GetGridDataDict()
        {
            return dUIConfigData;
        }
        public string GetSelectPara()
        {
            return sSelectPara;
        }
        public string GetViewFilePath()
        {
            return sSelectViewFilePath;
        }
        
        public List<string> GetOrder()
        {
            return DataOrder;
        }
        #endregion
    }

}
